﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
namespace ManageAzure
{
    public partial class RunPowerShellScript : Form
    {
        Runspace runspace;
        Pipeline pipeline;
        public RunPowerShellScript()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string scriptText = string.Empty;
            StringBuilder connectScript = new StringBuilder();
            string subsID = txtSubsID.Text;
            string subName = txtSubsName.Text;
            string certThumbNail = txtCertTumbnail.Text;
            
            //Script to connect
            string certDetail =  "$cert = Get-Item Cert:\\CurrentUser\\My\\" +certThumbNail;
            string connectCommandString = "Set-AzureSubscription -SubscriptionName $subsName -SubscriptionId $subid -Certificate $cert";
            string subNameParam = "$subsName='"+ subName+"'";
            string subIDParam = "$subid = '"+subsID+"'";

            connectScript.Append(subNameParam);
            connectScript.Append(Environment.NewLine);
            connectScript.Append(subIDParam);
            connectScript.Append(Environment.NewLine);
            connectScript.Append(certDetail);
            connectScript.Append(Environment.NewLine);
            connectScript.Append(connectCommandString);
            connectScript.Append(Environment.NewLine);

            // create Powershell runspace
            runspace = RunspaceFactory.CreateRunspace();
            // open it
            runspace.Open();
            // create a pipeline and feed it the script text
            pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(connectScript.ToString());
            
            pipeline.Commands.Add("Out-String");

            //    // execute the script
            Collection<PSObject> results = pipeline.Invoke();
            StringBuilder builder = new StringBuilder();
            if (pipeline.Error.Count > 0)
            {
                //iterate over Error PipeLine until end
                while (!pipeline.Error.EndOfPipeline)
                {
                    //read one PSObject off the pipeline
                    var value = pipeline.Error.Read() as PSObject;
                    if (value != null)
                    {
                        //get the ErrorRecord
                        var r = value.BaseObject as ErrorRecord;
                        if (r != null)
                        {
                            //build whatever kind of message your want
                            builder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
                            builder.AppendLine(r.InvocationInfo.PositionMessage);
                            builder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
                            builder.AppendLine(
                            string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
                        }
                    }
                }
            }

            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            string result = stringBuilder.ToString();


        }

        private void btnCreateService_Click(object sender, EventArgs e)
        {
            string serviceName = txtServiceName.Text;
            string serviceLabel = txtServiceLabel.Text;
            string affinityGroup = txtAffinity.Text;
            
            string serviceCommandString = "New-AzureService -ServiceName " + "'" + serviceName + "'" + " -Label " + "'" +serviceLabel +"'" + " -Location " +"'" + affinityGroup + "'";
            StringBuilder serviceCommandScript = new StringBuilder();
            serviceCommandScript.Append(serviceCommandString);
            serviceCommandScript.Append(Environment.NewLine);


            Pipeline pipeline = runspace.CreatePipeline();
            
            pipeline.Commands.AddScript(serviceCommandScript.ToString());
            pipeline.Commands.Add("Out-String");
            Collection<PSObject> results = pipeline.Invoke();

            StringBuilder builder = new StringBuilder();
            if (pipeline.Error.Count > 0)
            {
                //iterate over Error PipeLine until end
                while (!pipeline.Error.EndOfPipeline)
                {
                    //read one PSObject off the pipeline
                    var value = pipeline.Error.Read() as PSObject;
                    if (value != null)
                    {
                        //get the ErrorRecord
                        var r = value.BaseObject as ErrorRecord;
                        if (r != null)
                        {
                            //build whatever kind of message your want
                            builder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
                            builder.AppendLine(r.InvocationInfo.PositionMessage);
                            builder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
                            builder.AppendLine(
                            string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
                        }
                    }
                }
            }
  
            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            string result = stringBuilder.ToString();
        }

        private void btnDosconnect_Click(object sender, EventArgs e)
        {
            runspace.Close();
        }

        private void btnDeploy_Click(object sender, EventArgs e)
        {
            //tring certDetail = "$cert = Get-Item Cert:\\CurrentUser\\My\\" + certThumbNail;
            //string connectCommandString = "Set-AzureSubscription -SubscriptionName $subsName -SubscriptionId $subid -Certificate $cert";
            //string subNameParam = "$subsName='" + subName + "'";
            //string subIDParam = "$subid = '" + subsID + "'";

            string deploymentSlot = txtSlot.Text;
            string deploymentLabel = txtDeploymentLabel.Text;
            string packagePath = txtPackageFilePath.Text;
            string configFilePath = txtConfigFilePath.Text;
            string service = txtServiceName.Text;
            string subscriptionName = txtSubsName.Text;

            string storageAccountName = txtStorage.Text;
            string deploymentSlotVar = "$slot = '" + deploymentSlot + "'";
            string deploymentLabelVar = "$deploymentLabel = '" + deploymentLabel + "'";
            string packagePathVar = "$package = '" + packagePath + "'";
            string configFilePathVar = "$configuration = '" + configFilePath + "'";
            string storageAccountNameVar = "$storageAccount = '" + storageAccountName + "'";
            string serviceNameVar = "$service = '" + service + "'";
            string subscriptionNameVar = "$subscription = '" + subscriptionName + "'";

            StringBuilder serviceCommandScript = new StringBuilder();

            serviceCommandScript.Append(subscriptionNameVar);
            serviceCommandScript.Append(Environment.NewLine);
            serviceCommandScript.Append(serviceNameVar);
            serviceCommandScript.Append(Environment.NewLine);
            serviceCommandScript.Append(packagePathVar);
            serviceCommandScript.Append(Environment.NewLine);
            serviceCommandScript.Append(configFilePathVar);
            serviceCommandScript.Append(Environment.NewLine);
            serviceCommandScript.Append(storageAccountNameVar);
            serviceCommandScript.Append(Environment.NewLine);
            serviceCommandScript.Append(deploymentSlotVar);
            serviceCommandScript.Append(Environment.NewLine);
            serviceCommandScript.Append(deploymentLabelVar);
            serviceCommandScript.Append(Environment.NewLine);
            using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("ManageAzure.PowershellScripts.deploy.ps1")))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    serviceCommandScript.Append(line);
                    serviceCommandScript.Append(Environment.NewLine);
                }
            }

             Pipeline pipeline = runspace.CreatePipeline();
            
            pipeline.Commands.AddScript(serviceCommandScript.ToString());
            pipeline.Commands.Add("Out-String");
            Collection<PSObject> results = pipeline.Invoke();

            StringBuilder builder = new StringBuilder();
            if (pipeline.Error.Count > 0)
            {
                //iterate over Error PipeLine until end
                while (!pipeline.Error.EndOfPipeline)
                {
                    //read one PSObject off the pipeline
                    var value = pipeline.Error.Read() as PSObject;
                    if (value != null)
                    {
                        //get the ErrorRecord
                        var r = value.BaseObject as ErrorRecord;
                        if (r != null)
                        {
                            //build whatever kind of message your want
                            builder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
                            builder.AppendLine(r.InvocationInfo.PositionMessage);
                            builder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
                            builder.AppendLine(
                            string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
                        }
                    }
                }
            }
  
            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            string result = stringBuilder.ToString();

        } 
    }
}
